﻿using System;

namespace net.xBei.Helper {
    /// <summary>
    /// 枚举
    /// </summary>
    public static class EnumHelper {
        public static bool IsEnum<EnumType>(this string enumValue) where EnumType : struct
            => !string.IsNullOrWhiteSpace(enumValue) && Enum.IsDefined(typeof(EnumType), enumValue);
        public static bool IsEnum<EnumType>(this int enumValue) where EnumType : struct
            => Enum.IsDefined(typeof(EnumType), enumValue);
        /// <summary>
        /// 在指定枚举中检索具有指定值的常数的名称。<see cref="Enum.GetName(Type, object)"/>
        /// </summary>
        /// <typeparam name="EnumType"></typeparam>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetName<EnumType>(this EnumType enumValue) where EnumType : struct, Enum {
#if NETCOREAPP2_1
            return Enum.GetName(typeof(EnumType), enumValue);
#else
            return Enum.GetName(enumValue) ?? $"{enumValue}";
#endif
        }
        #region 解析
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="EnumType"></typeparam>
        /// <param name="enumValue"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static EnumType GetEnum<EnumType>(this string enumValue, EnumType dv) where EnumType : struct
            => Enum.TryParse<EnumType>(enumValue, true, out var result) ? result : dv;
        /// <summary>
        /// int转换到枚举
        /// </summary>
        /// <typeparam name="EnumType"></typeparam>
        /// <param name="enumValue"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static EnumType GetEnum<EnumType>(this int enumValue, EnumType dv) where EnumType : struct
            => Enum.TryParse<EnumType>($"{enumValue}", out var result) ? result : dv;
        /// <summary>
        /// int?转换到枚举
        /// </summary>
        /// <typeparam name="EnumType"></typeparam>
        /// <param name="enumValue"></param>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static EnumType GetEnum<EnumType>(this int? enumValue, EnumType dv) where EnumType : struct
            => enumValue.HasValue
                ? (Enum.TryParse<EnumType>($"{enumValue}", out var result) ? result : dv)
                : dv;
        #endregion
    }
}
